import {useStore} from "@/stores";

export function handleMenus(retMenus: any, menus: any) {
    if (menus) {
        menus.forEach((item: any) => {
            const props: any = item.props || [];
            const retItem = {
                ...item,
                ...props,
            };

            delete retItem.props;
            retMenus.push(retItem);

            if (item.children && item.children.length > 0) {
                retItem.children = [];
                handleMenus(retItem.children, item.children);
            }
        })
    }
}

export function handleLevelMenus(retMenus: any, menus: any, menuProps: any) {
    if (menus) {
        menus.forEach((item: any) => {
            const props: any = item.props || [];
            const retItem = {
                ...item,
                ...props,
            };

            menuProps && menuProps.forEach((mp: any) => {
                delete props[mp];
            });
            retItem.props = props;

            retMenus.push(retItem);
            if (item.children && item.children.length > 0) {
                retItem.children = [];
                handleLevelMenus(retItem.children, item.children, menuProps);
            }
        })
    }
}

export function handleResult(result: any, cols: any = undefined) {
    if (result && result.data) {
        result.data.forEach((item: any) => {
            if (item.props) {
                item.createTime = item.createTime || item.props.createTime || item.props.$createTime;
                item.lastLoginTime = item.props.$lastLoginTime || '';
                if (cols) {
                    cols.forEach((col: any) => {
                        item[col] = item.props[col];
                        delete item.props[col];
                    })
                }

                delete item.props.$createTime;
                delete item.props.$updateTime;
                delete item.props.$lastLoginTime;
            }
        })
    }
}

export const filterLevelData = (parent: any, item: any, filterCb: any) => {
    let newItem: any;
    // 1: 存在；0：不存在且不检查子节点
    const existTag: number = filterCb(item, parent);

    if (existTag == 1) {
        newItem = {...item};
        newItem.children = undefined;
    }

    if (0 != existTag && item.children && item.children.length > 0) {
        item.children.forEach((child: any) => {
            const newChild = filterLevelData(item, child, filterCb);
            if (newChild) {
                if (!newItem) {
                    newItem = {...item};
                    newItem.children = [];
                }

                if (!newItem.children) {
                    newItem.children = [];
                }

                newItem.children.push(newChild);
            }
        })
    }

    return newItem;
}


export const filterTreeList = (data: any, filterCb: any) => {
    const newData: any = [];
    if (!filterCb) {
        return data;
    }
    data.forEach((item: any) => {
        const newItem: any = filterLevelData(undefined, item, filterCb);
        if (newItem) {
            newData.push(newItem);
        }
    })
    return newData;
}

/**
 * 处理树形的资源数据
 * @param retMenus 返回资源数据
 * @param data 从服务器获取的原始数据
 * @param filterProps 需要删除的属性
 */
export function handleLevelData(retMenus: any, data: any, filterProps: any) {
    if (data) {
        data.forEach((item: any) => {
            const props: any = item.props || item.brief?.props || [];
            delete item.brief?.props;

            const retItem = {
                ...item,
                ...item.brief,
                ...props,
            };

            filterProps && filterProps.forEach((mp: any) => {
                delete props[mp];
            });
            retItem.props = props;

            retMenus.push(retItem);
            if (item.children && item.children.length > 0) {
                retItem.children = [];
                handleLevelData(retItem.children, item.children, filterProps);
            }
        })
    }
}

export function getStateText(state: number) {
    return state === 0 ? '待激活' :
        state === 1 ? '正常' :
            state === 2 ? '已禁用' : '已删除';
}

export function getStateTag(state: number) {
    return state === 0 ? 'info' :
        state === 1 ? 'success' :
            state === 2 ? 'warning' : 'danger';
}

export function getStateOptions(showAll: boolean = false, showDel: boolean = false) {
    const options: any[] = [];

    if (showAll) {
        options.push({
            value: -1,
            label: '全部'
        })
    }

    options.push({
        value: 0,
        label: '待激活'
    })
    options.push({
        value: 1,
        label: '正常'
    })
    options.push({
        value: 2,
        label: '禁用'
    });

    if (showDel) {
        options.push({
            value: 3,
            label: '已删除'
        })
    }

    return options;
}

export function setCookie(name: string, val: string, exDays: number): void {
    const d: Date = new Date();
    d.setTime(d.getTime() + (exDays * 24 * 60 * 60 * 1000));
    const expires: any = "expires=" + d.toUTCString();
    document.cookie = name + "=" + val + "; " + expires;
}

export function getCookie(cname: string) {
    const name: string = cname + "=";
    const ca: string[] = document.cookie.split(';');

    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) != -1) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

export function clearCookie(name: string) {
    setCookie(name, "", -1);
}

export function setItem(name: string, val: string) {
    localStorage.setItem(name, val);
}

export function getItem(name: string) {
    return localStorage.getItem(name);
}

export function removeItem(name: string) {
    localStorage.removeItem(name);
}

export function getAssetPath(url: string) {
    if (!url) {
        return '';
    }

    if (url.indexOf('http://') === 0 ||
        url.indexOf('https://') === 0) {
        return url;
    } else {
        const store = useStore();
        return store.settings['resourceUrl'] + url;
    }
}

export const exportAssets = async (url: string, params: any, config: any) => requestForm({
    url: url, method: 'get', data: {},
    responseType: 'blob',
    params: params,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    ...config
});

export async function downloadData(url: string, params: any, filename: any, config: any) {
    const downloadLoadingInstance = ElLoading.service({
        text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)",
    })
    const result: any = await exportAssets(url, params, config);
    console.log('--- download, 调用接口返回', result);
    if (result) {
        const isBlob = blobValidate(result);
        if (isBlob) {
            const blob = new Blob([result])
            saveAs(blob, filename)
        } else {
            showError('数据格式错误');
        }
        downloadLoadingInstance.close();
    } else {
        showError('下载文件出现错误，请联系管理员！')
        downloadLoadingInstance.close();
    }
}

export async function exportSystemDict(params: any, filename: any, config: any) {
    msgConfirm("是否确定导出字典？", async () => {
        await downloadData('/uni-center/v1/excel/dict/export', params, filename, config);
    })
}

export async function exportPlatformAsset(params: any, filename: any, config: any) {
    msgConfirm("是否确定导出资源？", async () => {
        await downloadData('/uni-center/v1/excel/asset/export/platform', params, filename, config);
    })
}

export async function exportAssetByType(params: any, filename: any, config: any) {
    msgConfirm("是否确定导出资源？", async () => {
        await downloadData('/uni-center/v1/excel/asset/export/type', params, filename, config);
    })
}
